import os
import subprocess


class AudioReplacer:
    """
    批量替换视频中的音频轨道工具类。
    使用 ffmpeg 实现：将视频原有音轨替换为指定音频文件。
    """

    def __init__(self, video_folder=None, audio_folder=None, output_folder=None):
        """
        初始化

        Args:
            video_folder (str): 视频文件夹路径
            audio_folder (str): 音频文件夹路径
            output_folder (str): 输出文件夹路径
        """
        self.video_folder = video_folder
        self.audio_folder = audio_folder
        self.output_folder = output_folder

    # ===== Setter 方法 =====
    def set_video_folder(self, path: str):
        """设置视频文件夹路径"""
        self.video_folder = path

    def set_audio_folder(self, path: str):
        """设置音频文件夹路径"""
        self.audio_folder = path

    def set_output_folder(self, path: str):
        """设置输出文件夹路径"""
        self.output_folder = path

    # ===== 主功能函数 =====
    def replace_audio_tracks(self):
        """执行批量音频替换操作"""
        if not all([self.video_folder, self.audio_folder, self.output_folder]):
            raise ValueError("❌ 请先设置 video_folder、audio_folder 和 output_folder")

        os.makedirs(self.output_folder, exist_ok=True)

        # 视频文件列表
        video_files = [f for f in os.listdir(self.video_folder)
                       if os.path.splitext(f)[1].lower() in (".mp4", ".mkv", ".mov", ".avi", ".flv", ".wmv")]

        if not video_files:
            print("⚠️ 未找到任何视频文件。")
            return

        print(f"🎬 检测到 {len(video_files)} 个视频文件，开始处理...\n")

        for video_file in video_files:
            video_name, video_ext = os.path.splitext(video_file)
            video_path = os.path.join(self.video_folder, video_file)

            # 查找同名音频
            found_audio = False
            for audio_ext in (".mp3", ".wav", ".aac", ".flac"):
                audio_path = os.path.join(self.audio_folder, video_name + audio_ext)
                if os.path.exists(audio_path):
                    found_audio = True
                    output_path = os.path.join(self.output_folder, video_name + video_ext)

                    # ffmpeg 命令
                    command = [
                        "ffmpeg", "-y",
                        "-i", video_path, "-i", audio_path,
                        "-c:v", "copy",
                        "-map", "0:v:0",
                        "-map", "1:a:0",
                        "-shortest",
                        output_path
                    ]

                    print(f"🎧 正在处理：{video_file} + {os.path.basename(audio_path)}")
                    subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                    print(f"✅ 完成：{output_path}\n")
                    break

            if not found_audio:
                print(f"⚠️ 未找到匹配音频：{video_name}")

        print("🎉 所有文件处理完成！")

# ============ 使用示例 ============
if __name__ == "__main__":
    replacer = AudioReplacer(
        video_folder=r"C:\Users\33720\Desktop\好多好多日语句子\好多好多日语句子",
        audio_folder=r"C:\Users\33720\Desktop\好多好多日语句子\好多好多日语句子cmp3",
        output_folder=r"C:\Users\33720\Desktop\好多好多日语句子\好多好多日语句子OVER"
    )

    # 你也可以这样动态修改路径：
    # replacer.set_audio_folder(r"D:\new_audio")
    # replacer.set_output_folder(r"D:\output_videos")

    replacer.replace_audio_tracks()
